package com.passwordmanager.activities;

import java.sql.SQLException;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;
import com.j256.ormlite.dao.Dao;
import com.passwordmanager.data.Password;
import com.passwordmanager.manager.DatabaseHelper;

public class PasswordManager extends OrmLiteBaseActivity<DatabaseHelper> {
	String key;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    	try {
    		if (key == null && getIntent().getStringExtra("password") != null && ("").equals(getIntent().getStringExtra("password"))){
            	key = getIntent().getStringExtra("password");
            }
    		
    		boolean passWordExist = passWordExist();
    		
    		if (key == null && !passWordExist) {
				Intent intent = new Intent(PasswordManager.this, createPassword.class);
				startActivity(intent);
			} else if (key == null && passWordExist) {
				Intent intent = new Intent(PasswordManager.this, Login.class);
				startActivity(intent);
			} else {
				Log.e(PasswordManager.class.getName(), "liste password !!");
			}
    		
		} catch (Exception e) {
			Log.e("Error", "error on PasswordManager" + e);
		}
		
    }
    
    public boolean passWordExist() throws SQLException{
    	Dao<Password, Integer> passwordDao = getHelper().getPasswordDao();
    	long countOf = passwordDao.countOf();
    	Log.i(PasswordManager.class.getName(), "nb : " + String.valueOf(countOf));
    	return countOf > 0;
    }
    
    @Override
    public void onSaveInstanceState(Bundle outState) {
    	if (key != null)
    		outState.putString("password", key);
    	super.onSaveInstanceState(outState);
    }
    
    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
	  super.onRestoreInstanceState(savedInstanceState);
	  key = savedInstanceState.getString("password");
	}
}